package com.zhao.retry.demo;

import com.zhao.retry.demo.entity.HttpRetryRecord;
import com.zhao.retry.demo.mapper.HttpRetryRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created on 2020/5/20.
 *
 * @author zhao
 * @email 136689260@qq.com
 */
@Component
public class RetryClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    @Autowired
    private HttpRetryRecordMapper httpRetryRecordMapper;

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] bytes, ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, bytes);
        HttpRetryRecord httpRetryRecord = new HttpRetryRecord();
        httpRetryRecord.setHttpUri(request.getURI().toString());
        httpRetryRecord.setMethodValue(request.getMethodValue());
        httpRetryRecord.setHeaders(request.getHeaders());
        httpRetryRecord.setStatusCode(response.getRawStatusCode());
        httpRetryRecordMapper.insert(httpRetryRecord);
        return response;
    }
}
